package site.zhanjingbo.shop.web.controller;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import site.zhanjingbo.shop.meta.Product;
import site.zhanjingbo.shop.service.ProductService;
import site.zhanjingbo.shop.utils.Permission;
import site.zhanjingbo.shop.utils.PermissionType;
import site.zhanjingbo.shop.utils.ResponseType;

@Controller
public class ProductController {

	@Resource
	private ProductService productService;

	@Permission(permission = PermissionType.SELLER)
	@RequestMapping("/public")
	public String publicPage() {
		return "public";
	}

	@Permission(permission = PermissionType.SELLER)
	@RequestMapping("/publicSubmit")
	public ModelAndView publicSubmit(Product product) {
		ModelAndView mav = new ModelAndView();
		boolean flag = productService.addProduct(product);
		if (flag == true) {
			mav.addObject("product", product);
		}
		mav.setViewName("publicSubmit");
		return mav;
	}

	@RequestMapping("/show")
	public ModelAndView show(int id) {
		ModelAndView mav = new ModelAndView();
		Product product = productService.getProductById(id);
		if (product != null) {
			mav.addObject("product", product);
		}
		mav.setViewName("show");
		return mav;
	}

	@Permission(permission = PermissionType.SELLER)
	@RequestMapping("/edit")
	public ModelAndView edit(int id) {
		ModelAndView mav = new ModelAndView();

		Product product = productService.getProductById(id);
		if (product != null) {
			mav.addObject("product", product);
		}
		mav.setViewName("edit");

		return mav;
	}

	@Permission(permission = PermissionType.SELLER)
	@RequestMapping("/editSubmit")
	public ModelAndView editSubmit(Product product) {
		ModelAndView mav = new ModelAndView();

		boolean flag = productService.updateProduct(product);
		if (flag == true) {
			mav.addObject("product", product);
		}
		mav.setViewName("editSubmit");
		return mav;
	}

	@Permission(permission = PermissionType.SELLER, response = ResponseType.PAGE)
	@RequestMapping(value = "/api/delete", method = RequestMethod.POST)
	public Map<String, Object> deleteProduct(int id, HttpServletResponse response) {
		Map<String, Object> result = new HashMap<>();
		boolean flag = productService.deleteProduct(id);
		response.setStatus(300);
		if (flag) {
			result.put("message", "删除成功");
			response.setStatus(200);
		}
		result.put("code", response.getStatus());
		result.put("result", flag);
		return result;
	}

}
